package com.iter.devbox.httpclient;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * HttpClient工具类
 * 
 * @author hnylj
 */
public class HttpClientUtils {

	public static String doGet(String url) {
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		String result = "";
		try {
			httpclient = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet(url);
			response = httpclient.execute(httpGet);
		
		    System.out.println(response.getStatusLine());
		    HttpEntity entity = response.getEntity();
		    result = EntityUtils.toString(entity);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		} finally {
		    try {
		    	if (null != response) {
		    		response.close();
		    	}
		    	if (null != httpclient) {
		    		httpclient.close();
		    	}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	
	public static String doPost(String url, Map<String, String> paramMap) {
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		String result = "";
		try {
			httpclient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			
			Set<Map.Entry<String, String>> set = paramMap.entrySet();
			Iterator<Map.Entry<String, String>> it = set.iterator();
			while (it.hasNext()) {
				Map.Entry<String, String> mapEntry = it.next();
				nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue()));
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nvps));
			response = httpclient.execute(httpPost);
		
		    System.out.println(response.getStatusLine());
		    HttpEntity entity = response.getEntity();
		    
		    result = EntityUtils.toString(entity);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
		    	if (null != response) {
		    		response.close();
		    	}
		    	if (null != httpclient) {
		    		httpclient.close();
		    	}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}
}
